package com.jarveis.dbs.core.init;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.jarveis.dbs.core.DBService;
import com.jarveis.dbs.core.DBServiceImpl;
import com.jarveis.frame.lang.StringUtil;
import com.jarveis.frame.util.Param;

/**
 * 数据访问入口
 * 
 * @author liuguojun
 * @date 2014-06-05
 */

public class DBS4Servlet extends HttpServlet {

	private static final Logger logger = Logger.getLogger(DBS4Servlet.class);
	private static final String CONTENT_TYPE = "text/plain; charset=UTF-8";
	private static final String SERVICE_ID = "dbs";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		process(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		process(req, resp);
	}

	/**
	 * 处理
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	private void process(HttpServletRequest req, HttpServletResponse resp) {
		try {
			String uri = req.getRequestURI();
			Pattern pattern = Pattern.compile("([a-zA-Z0-9]+)(\\.service)");
            Matcher matcher = pattern.matcher(uri);
            String serviceId = null;
            if(matcher.find()) {
            	serviceId = matcher.group(1);
            }
			
            String message = null;
            if (SERVICE_ID.equals(serviceId)) {
            	message = req.getParameter("_message");
            } else {
            	Map map = req.getParameterMap();
            	Param in = new Param(Param.REQ);
            	in.getHead().setProperty("@device", StringUtil.getUUID());
            	in.getHead().setProperty("@funcId", serviceId);
            	in.getHead().setProperty("@dataType", "json");
            	in.getBody().setPropertys(map);
            	message = in.toJsonString();
            }
			
			if (!StringUtil.isEmpty(message)) {
				DBService dbservice = new DBServiceImpl();
				message = dbservice.process(message);
				print(resp, message);
			} else {
				print(resp, Param.ERROR_SUCCESS);
			}
		} catch (Exception ex) {
			print(resp, Param.ERROR_SUCCESS);
		}
	}

	/**
	 * 输出
	 * 
	 * @param resp
	 * @param message
	 */
	protected void print(HttpServletResponse resp, String message) {
		try {
			resp.setContentType(CONTENT_TYPE);
			resp.setHeader("Pragma", "No-cache");
			resp.setHeader("Cache-Control", "no-cache");
			resp.setDateHeader("Expires", 0);
			PrintWriter write = resp.getWriter();
			write.print(message);
			write.close();
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
	}

}
